﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DeviceUnion.FFmpeg.WinForm
{
    public abstract class Recorder : IRecorder
    {
        internal System.Diagnostics.Process CmdProcess { get; set; }
        public event EventHandler<LogEventArgs> OnCmdOutput;

        public Recorder()
        {
            CmdProcess = new System.Diagnostics.Process();
            CmdProcess.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            CmdProcess.StartInfo.EnvironmentVariables.Add("ffmpeg", System.IO.Path.Combine(CmdProcess.StartInfo.WorkingDirectory, "ffmpeg.exe"));
            CmdProcess.StartInfo.FileName = "cmd";
            CmdProcess.StartInfo.Verb = "-runas";
            CmdProcess.StartInfo.RedirectStandardInput = true;
            CmdProcess.StartInfo.RedirectStandardOutput = true;
            CmdProcess.StartInfo.RedirectStandardError = true;
            CmdProcess.StartInfo.UseShellExecute = false;
            CmdProcess.StartInfo.CreateNoWindow = true;
            CmdProcess.OutputDataReceived -= Handle_OutputDataReceived;
            CmdProcess.OutputDataReceived += Handle_OutputDataReceived;
            CmdProcess.ErrorDataReceived -= Handle_OutputDataReceived;
            CmdProcess.ErrorDataReceived += Handle_OutputDataReceived;
        }

        private void Handle_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            OnCmdOutput?.Invoke(this, new LogEventArgs(e.Data));
        }

        public void Dispose()
        {
            if (!CmdProcess.HasExited)
                CmdProcess.Kill();
        }

        public virtual void Open()
        {
            CmdProcess.Start();
            CmdProcess.BeginErrorReadLine();
            CmdProcess.BeginOutputReadLine();
        }

        public virtual void Close()
        {
            CmdProcess.StandardInput.WriteLine("q");
            CmdProcess.StandardInput.WriteLine("exit");
        }

        public virtual void StopRecord()
        {
            CmdProcess.StandardInput.WriteLine("q");
        }

        public abstract void StartRecordDesktop(FFParam param);
        public abstract void StartRecordWindow(FFParam param);
        public abstract void StartRecordDesktop(string file);
        public abstract void StartRecordDesktop(string file, uint duration);
        public abstract void StartRecordDesktop(string file, uint duration, string waterMarkStr);
        public abstract void StartRecordDesktop(string file, int x, int y, int w, int h);
        public abstract void StartRecordWindow(string window, string file);
        public abstract void StartRecordWindow(string window, string file, uint duration);
        public abstract void StartRecordWindow(string window, string file, uint duration, string waterMarkStr);

    }
}
